
package com.supercwn.player.app.manager.util;

import android.content.Context;
import android.content.Intent;
import android.content.pm.IPackageStatsObserver;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.PackageStats;
import android.content.pm.ResolveInfo;
import android.os.Environment;
import android.os.RemoteException;
import android.os.StatFs;
import android.text.format.Formatter;
import android.util.Log;


import com.supercwn.player.app.manager.bean.AppBean;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 读取设备上所有的APP
 */
public class ReadAllAppUtil {

    private Context mContext;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
    private static final String MAIN = "android.intent.action.MAIN";
    private static final String LAUNCHER = "android.intent.category.LAUNCHER";
    private static volatile ReadAllAppUtil readAllAppUtil;

    private ReadAllAppUtil(Context context) {
        mContext = context;
    }

    public static synchronized ReadAllAppUtil getInstance(Context context) {
        if (readAllAppUtil == null) {
            readAllAppUtil = new ReadAllAppUtil(context);
        }
        return readAllAppUtil;
    }

    private static final String TAG = "TGH";

    public List<AppBean> getLaunchAppList() {
        PackageManager localPackageManager = mContext.getPackageManager();
        Intent localIntent = new Intent(MAIN);
        localIntent.addCategory(LAUNCHER);
        List<ResolveInfo> localList = localPackageManager.queryIntentActivities(localIntent, 0);
        List<AppBean> localArrayList = null;
        Iterator<ResolveInfo> localIterator = null;
        if (localList != null) {
            localArrayList = new ArrayList<>();
            localIterator = localList.iterator();
        }
        while (true) {
            if (localIterator != null) {
                if (!localIterator.hasNext())
                    break;
                ResolveInfo localResolveInfo = (ResolveInfo) localIterator.next();
                AppBean localAppBean = new AppBean();
                localAppBean.setIcon(localResolveInfo.activityInfo.loadIcon(localPackageManager));
                localAppBean.setName(localResolveInfo.activityInfo.loadLabel(localPackageManager).toString());
                localAppBean.setPackageName(localResolveInfo.activityInfo.packageName);
                localAppBean.setDataDir(localResolveInfo.activityInfo.applicationInfo.publicSourceDir);
                localAppBean.setLauncherName(localResolveInfo.activityInfo.name);
                String pkgName = localResolveInfo.activityInfo.packageName;
                PackageInfo mPackageInfo;
                try {
                    mPackageInfo = mContext.getPackageManager().getPackageInfo(pkgName, 0);
                    if ((mPackageInfo.applicationInfo.flags & mPackageInfo.applicationInfo.FLAG_SYSTEM) > 0) {// 系统预装
                        localAppBean.setSysApp(true);
                    }
                } catch (NameNotFoundException e) {
                    e.printStackTrace();
                }
                String noSeeApk = localAppBean.getPackageName();

                /**
                 * 屏蔽自己
                 */
                if (!noSeeApk.equals("com.supercwn.player")) {
                    localArrayList.add(localAppBean);
                }
            }
        }
        return localArrayList;
    }

    public List getAllInstallApp() {
        List<PackageInfo> packageInfoList = mContext.getPackageManager().getInstalledPackages(0);
        List<AppBean> result = new ArrayList<>();
        for (PackageInfo packageInfo : packageInfoList) {
            /*
             * 判断是否为非系统应用
             * */
            AppBean app = new AppBean();
            app.setIcon(packageInfo.applicationInfo.loadIcon(mContext.getPackageManager()));
            app.setName(packageInfo.applicationInfo.loadLabel(mContext.getPackageManager()).toString());
            app.setPackageName(packageInfo.packageName);
            app.setVersionName(packageInfo.versionName);
            getPkgSize(mContext, packageInfo.packageName, app);
            long firstInstallTime = packageInfo.firstInstallTime;
            app.setFirstInstallTime(sdf.format(firstInstallTime));
            if ((packageInfo.applicationInfo.flags & packageInfo.applicationInfo.FLAG_SYSTEM) > 0) {// 系统预装
                app.setSysApp(true);
                Log.i("TGH", "系统应用");
            } else {
                /**如果为系统app就不加入到集合中**/
                /**
                 * 屏蔽自己
                 */
                String noSeeApk = app.getPackageName();
                if (!noSeeApk.equals("com.supercwn.player")) {
                    result.add(app);
                }
            }
        }
        return result;
    }


    public List<AppBean> getUninstallAppList() {
        PackageManager localPackageManager = mContext.getPackageManager();
        Intent localIntent = new Intent(MAIN);
        localIntent.addCategory(LAUNCHER);
        List<ResolveInfo> localList = localPackageManager.queryIntentActivities(localIntent, 0);
        List<AppBean> localArrayList = null;
        Iterator<ResolveInfo> localIterator = null;
        if (localList != null) {
            localArrayList = new ArrayList<>();
            localIterator = localList.iterator();
        }
        while (true) {
            if (localIterator != null) {
                if (!localIterator.hasNext())
                    break;
                ResolveInfo localResolveInfo = (ResolveInfo) localIterator.next();
                AppBean localAppBean = new AppBean();
                localAppBean.setIcon(localResolveInfo.activityInfo.loadIcon(localPackageManager));
                localAppBean.setName(localResolveInfo.activityInfo.loadLabel(localPackageManager).toString());
                localAppBean.setPackageName(localResolveInfo.activityInfo.packageName);
                localAppBean.setDataDir(localResolveInfo.activityInfo.applicationInfo.publicSourceDir);
                String pkgName = localResolveInfo.activityInfo.packageName;
                PackageInfo mPackageInfo;
                try {
                    mPackageInfo = mContext.getPackageManager().getPackageInfo(pkgName, 0);
                    if ((mPackageInfo.applicationInfo.flags & mPackageInfo.applicationInfo.FLAG_SYSTEM) > 0) {// 系统预装
                        localAppBean.setSysApp(true);
                    } else {
                        localArrayList.add(localAppBean);
                    }
                } catch (NameNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        return localArrayList;
    }

    public List<AppBean> getAutoRunAppList() {
        PackageManager localPackageManager = mContext.getPackageManager();
        Intent localIntent = new Intent(MAIN);
        localIntent.addCategory(LAUNCHER);
        List<ResolveInfo> localList = localPackageManager.queryIntentActivities(localIntent, 0);
        List<AppBean> localArrayList = null;
        Iterator<ResolveInfo> localIterator = null;
        if (localList != null) {
            localArrayList = new ArrayList<>();
            localIterator = localList.iterator();
        }

        while (true) {
            if (localIterator != null) {
                if (!localIterator.hasNext())
                    break;
                ResolveInfo localResolveInfo = localIterator.next();
                AppBean localAppBean = new AppBean();
                localAppBean.setIcon(localResolveInfo.activityInfo.loadIcon(localPackageManager));
                localAppBean.setName(localResolveInfo.activityInfo.loadLabel(localPackageManager).toString());
                localAppBean.setPackageName(localResolveInfo.activityInfo.packageName);
                localAppBean.setDataDir(localResolveInfo.activityInfo.applicationInfo.publicSourceDir);
                String pkgName = localResolveInfo.activityInfo.packageName;
                String permission = "android.permission.RECEIVE_BOOT_COMPLETED";
                try {
                    PackageInfo mPackageInfo = mContext.getPackageManager().getPackageInfo(pkgName, 0);
                    if ((PackageManager.PERMISSION_GRANTED == localPackageManager.checkPermission(permission, pkgName))
                            && !((mPackageInfo.applicationInfo.flags & mPackageInfo.applicationInfo.FLAG_SYSTEM) > 0)) {
                        localArrayList.add(localAppBean);
                    }
                } catch (NameNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        return localArrayList;
    }

    /**
     * 获得App应用的大小
     *
     * @param context
     * @param pkgName
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public static void getPkgSize(final Context context, String pkgName, final AppBean appInfo) {
        // getPackageSizeInfo是PackageManager中的一个private方法，所以需要通过反射的机制来调用
        Method method = null;
        try {
            method = PackageManager.class.getMethod("getPackageSizeInfo",
                    String.class, IPackageStatsObserver.class);
            // 调用 getPackageSizeInfo 方法，需要两个参数：1、需要检测的应用包名；2、回调
            method.invoke(context.getPackageManager(), pkgName,
                    new IPackageStatsObserver.Stub() {
                        @Override
                        public void onGetStatsCompleted(PackageStats pStats, boolean succeeded) throws RemoteException {
                            // 从pStats中提取各个所需数据
                            Log.i(TAG, "" + "缓存大小=" + Formatter.formatFileSize(context, pStats.cacheSize) +
                                    "\n数据大小=" + Formatter.formatFileSize(context, pStats.dataSize) +
                                    "\n程序大小=" + Formatter.formatFileSize(context, pStats.codeSize));
                            if (appInfo != null) {
                                appInfo.setCacheSize(Formatter.formatFileSize(context, pStats.cacheSize));
                                appInfo.setDataSize(Formatter.formatFileSize(context, pStats.dataSize));
                                appInfo.setCodeSize(Formatter.formatFileSize(context, pStats.codeSize));
                                appInfo.setAppSize(Formatter.formatFileSize(context, (pStats.codeSize + pStats.dataSize + pStats.cacheSize)));
                            }
                        }
                    });
        } catch (IllegalAccessException e) {
            Log.i(TAG, "1  :" + e);
        } catch (InvocationTargetException e) {
            Log.i(TAG, "2  :" + e);
        } catch (NoSuchMethodException e) {
            Log.i(TAG, "3  :" + e);
        }


    }


    /****新写入***/
    /**
     * 获得SD卡总大小
     *
     * @return
     */
    public String getSDTotalSize() {
        File path = Environment.getExternalStorageDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long totalBlocks = stat.getBlockCount();
        return Formatter.formatFileSize(mContext, blockSize * totalBlocks);
    }

    /**
     * 获得sd卡剩余容量，即可用大小
     *
     * @return
     */
    public String getSDAvailableSize() {
        File path = Environment.getExternalStorageDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return Formatter.formatFileSize(mContext, blockSize * availableBlocks);
    }

    /**
     * 获得机身内存总大小
     *
     * @return
     */
    public String getRomTotalSize() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long totalBlocks = stat.getBlockCount();
        return Formatter.formatFileSize(mContext, blockSize * totalBlocks);
    }

    /**
     * 获得机身可用内存
     *
     * @return
     */
    public String getRomAvailableSize() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return Formatter.formatFileSize(mContext, blockSize * availableBlocks);
    }


}